﻿using System.Collections.Generic;
using Foothill.Common;
using Foothill.Model;
using Foothill.Service;
using Foothill.Service.AdService;
using Foothill.Service.MiscInfo;
using Foothill.Service.Session;
using Foothill.Service.SystemMessage;
using Foothill.Service.VehicleInfo;
using Foothill.Service.Security;
using Foothill.Service.Validation;

namespace Foothill.Web.Presenter
{
    public class PostForSalePresenter : FoothillBasePresenter
    {
        private IPostForSaleView _view;
        private ISecurityService _securityService;
        private ISessionService _sessionService;
        private IMiscInfoService _miscInfoService;
        private IVehicleInfoService _vehicleInfoService;
        private ISystemMessageService _systemMessageService;
        private IPostValidator _validator;
        private IValidationService _validationService;  

        private bool _isCurrentUserAuthenticated;

        public IPostForSaleView View
        {
            set { _view = value; }
            get { return _view; }
        }

        public PostForSalePresenter(ISessionService sessionManager,
            IVehicleInfoService vehicleInfoService, IMiscInfoService miscInfoService, ISystemMessageService systemMessageService,
            IPostValidator validator, ISecurityService securityService, IValidationService validationService)
        {
            _sessionService = sessionManager;
            _vehicleInfoService = vehicleInfoService;
            _miscInfoService = miscInfoService;
            _systemMessageService = systemMessageService;
            _validator = validator;
            _securityService = securityService;
            _validationService = validationService;

            _isCurrentUserAuthenticated = _securityService.IsCurrentUserAuthenticated();
        }

        // initialize controls on the page
        public void InitPage()
        {
            InitMakeList();
            InitModelList();
            InitYearList();
            InitCityList();
            InitControlsForLoginUser();
        }

        private void InitMakeList()
        {
            _view.PopulateVehicleMake(_vehicleInfoService.GetVehicleMakes());
        }

        private void InitControlsForLoginUser()
        {
            if (_isCurrentUserAuthenticated)
            {
                CurrentLoginUser loginUser = _securityService.GetLoginUserDetails();

                if (loginUser != null)
                {
                    _view.PopulateContactInformation(loginUser.UserAccountInfo.ContactName, loginUser.UserAccountInfo.Email, loginUser.UserAccountInfo.ContactPhone);
                }
            }
        }

        private void InitModelList()
        {
            IDictionary< int, string> dict = new Dictionary<int,string>();
            _view.PopulateVehicleModel(dict);
        }

        private void InitYearList()
        {
            _view.PopulateYearList(Utility.GetYearDict());
        }

        private void InitCityList()
        {
            _view.PopulateCityList(_miscInfoService.GetCities((int)Provinces.BC));       
        }
        
        public void VehicleMakeSelected( int selectedMakeId )
        {
            // get model list and populate the model dropdown
            _view.PopulateVehicleModel(_vehicleInfoService.GetVehicleModels(selectedMakeId));            
        }

        // user clicked on "submit" button on view
        public void TrySubmitNewAd(ForSaleAd newAd)
        {
            IDictionary<PostForSaleFields, string> retDict = new Dictionary<PostForSaleFields, string>();

            // validate the user inputs
            if (!Validate(newAd, out retDict))
            {
                // not valid
                _view.DisplayInvalidPageMessage(retDict);
            }
            else
            {
                // sanitize description text
                _validationService.SanitizeHtml(newAd.Description);
                
                if (_isCurrentUserAuthenticated)
                {
                    newAd.PostedByUserAccountId = _securityService.GetLoginUserId();
                }
                
                // save the newAd into session
                _sessionService.SaveSessionValue(SessionNames.NewForSaleAd, newAd);

                // and redirect to upload images
                _view.RedirectToUploadPhotoPage();
            }
        }

        /// <summary>
        /// validate a new Ad a user trying to post
        /// </summary>
        /// <param name="newAd">the new Ad to post</param>
        /// <param name="retDict">property that failed validation and error msg</param>
        private bool Validate(ForSaleAd newAd, out IDictionary<PostForSaleFields, string> retDict)
        {
            return _validator.ValidateForSaleAd(newAd, out retDict);
        }
    }
}